package com.spit.fammo.ui.frg

import android.os.Bundle
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.viewModelScope
import com.spit.amoeba.base.BaseFragment
import com.spit.fammo.R
import com.spit.fammo.databinding.FPowerSettingBinding
import com.spit.fammo.ext.showMessage
import com.spit.fammo.viewmodel.PowerSettingModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * User: Nike
 *  2025/1/14 16:17
 *      配置天线
 */
class PowerSettingFrg: BaseFragment<PowerSettingModel, FPowerSettingBinding>(){

    override fun initView(savedInstanceState: Bundle?) {

        mDatabind.viewmodel = mViewModel
        mDatabind.click = ProxyClick()

        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onResume(owner: LifecycleOwner) {
                super.onResume(owner)
                setToolBarTitle(getString(R.string.home_settings))
                setpower()
            }
        })

        mDatabind.seekbar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener{
            override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
                mViewModel.powerNum.set(getString(R.string.settingAntennaPower_title) + "：${p1}")
            }

            override fun onStartTrackingTouch(p0: SeekBar?) {

            }

            override fun onStopTrackingTouch(p0: SeekBar?) {

            }
        })
    }

    inner class ProxyClick() {

        fun onConfirm(){
            mViewModel.viewModelScope.launch(Dispatchers.IO) {
                val bean = mViewModel.configDao.findFirst()
                bean.power = mDatabind.seekbar.progress
                bean.speed = if (mDatabind.spSpeed.selectedItemPosition == 0) 1 else 3
                bean.session = mDatabind.spSession.selectedItemPosition
                bean.inventoryFlag = mDatabind.spMode.selectedItemPosition
                mViewModel.configDao.update(bean)
                withContext(Dispatchers.Main) {
                    showMessage(getString(R.string.success))
                }
            }
        }

        fun onCancel(){
            setpower()
        }

    }

    fun setpower(){
        mViewModel.viewModelScope.launch(Dispatchers.IO) {
            val bean = mViewModel.configDao.findFirst()
            withContext(Dispatchers.Main) {
                mDatabind.seekbar.progress = bean.power
                mDatabind.spSpeed.setSelection(if (bean.speed == 1) 0 else 1)
                mDatabind.spSession.setSelection(bean.session)
                mDatabind.spMode.setSelection(bean.inventoryFlag)
            }
        }
    }

}